﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Domains.zjy;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using Yitter.IdGenerator;

namespace RearLivestock.Beginning.Api.Application.Command.PrenatalCheckup
{
    /// <summary>
    /// 添加种母妊检
    /// </summary>
    public class CreatePrenatalCheckupHandler : IRequestHandler<CreatePrenatalCheckupCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 猪只档案仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> _basicInformationRepository;

        /// <summary>
        /// 种母妊检仓储
        /// </summary>
        private readonly IBaseRepository<PrenatalCheckups> _prenatalCheckupsRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreatePrenatalCheckupCommand> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="prenatalCheckupsRepository"></param>
        /// <param name="basicInformationRepository"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public CreatePrenatalCheckupHandler(IBaseRepository<PrenatalCheckups> prenatalCheckupsRepository,
                                            IBaseRepository<BasicInformation> basicInformationRepository,
                                            ILogger<CreatePrenatalCheckupCommand> logger,
                                            IMapper mapper)
        {
            _prenatalCheckupsRepository = prenatalCheckupsRepository;
            _basicInformationRepository = basicInformationRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 添加种母妊检
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreatePrenatalCheckupCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //将数据保存到mapper中
                //PrenatalCheckups prenatal = _mapper.Map<PrenatalCheckups>(request);

                //单据号尾数
                var num = 1001;
                //遍历前台传入后台的值
                foreach (var item in request.PrenatalCheckups)
                {
                    //循环添加流水号 雪花ID
                    item.SerialNumber = YitIdHelper.NextId().ToString();
                    //循环添加单据号
                    item.DocumentNumber = DateTime.Now.ToString("yyyyMMddHHmmss") + num;
                    //时间
                    item.CreatedTime=item.CreatedTime.Value.AddHours(8);
                    //尾号自增
                    num++;
                    //根据前台传入的耳号id进行查询
                    var query = await (await _basicInformationRepository.GetAll()).Where(x => x.BasicInforId == item.BasicInforId).ToListAsync();
                    //循环修改猪只档案(基本信息) 种母的 妊检状态 以及 转入栋舍 栏位
                    query.ForEach(x =>
                    {
                        //将猪只档案的种母妊检状态修改为妊检
                        x.IsPrenatalCheckup = 2;
                        //转入栋舍 栏位
                        x.BedroomId = item.TurnBuilding;
                        x.FieldId = item.TurnColumn;
                    });
                    //修改猪只档案信息
                    _basicInformationRepository.UpdRange(query);
                }
                //批量添加数据
                var res = _prenatalCheckupsRepository.AddRange(request.PrenatalCheckups);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加种母妊检成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = ex.Message;
                _logger.LogError("添加种母妊检异常" + ex.Message);
            }
            return result;
        }
    }
}
